import 'dart:convert';

import 'log_util.dart';

class JsonUtil {
  static String toJson(dynamic value) {
    return value == null ? '' : json.encode(value);
  }

  static T? toObj<T>(dynamic source, T Function(Map<String, dynamic> v) f) {
    if (source == null || source.toString().isEmpty) return null;
    try {
      Map<String, dynamic> map;
      if (source is String) {
        map = json.decode(source);
      } else {
        map = source;
      }
      return f(map);
    } catch (e) {
      print('JsonUtils convert error, Exception：${e.toString()}');
    }
    return null;
  }

  static List<T>? toObjList<T>(dynamic source, T Function(Map<String, dynamic> v) f) {
    if (source == null || source.toString().isEmpty) return null;
    try {
      List list;
      if (source is String) {
        list = json.decode(source);
      } else {
        list = source;
      }
      return list.map((value) {
        if (value is String) {
          value = json.decode(value);
        }
        return f(value);
      }).toList();
    } catch (e) {
      LogUtil.e(msg:'JsonUtils convert error, Exception：${e.toString()}');
    }
    return null;
  }

  static List<T>? toList<T>(dynamic source) {
    List list;
    if (source is String) {
      list = json.decode(source);
    } else {
      list = source;
    }
    return list.map((v) {
      return v as T;
    }).toList();
  }

  static void printJson(Object object) {
    try {
      JsonEncoder encoder = const JsonEncoder.withIndent('  ');
      var encoderString = encoder.convert(object);
      LogUtil.e(msg: encoderString);
    } catch (e) {
      LogUtil.e(msg: e);
    }
  }

  static void printJsonEncode(Object object) {
    try {
      var encoderString = json.encode(object);
      LogUtil.e(msg: encoderString);
    } catch (e) {
      LogUtil.e(msg: e);
    }
  }
}
